#!/bin/bash
#
# Build a boot.iso by lorax. The boot.iso will be stored in the `/images/` directory.
# We have to build the RPMs files of Anaconda first and then add them as volume
# mount to /anaconda-rpms to the container (could be RO mount).
#
#   sudo make -f ./Makefile.am container-rpms-scratch
#   sudo podman run -i --rm --privileged --tmpfs /var/tmp:rw,mode=1777 -v `pwd`/result/build/01-rpm-build:/anaconda-rpms:ro -v `pwd`/output-dir:/images:z quay.io/rhinstaller/anaconda-iso-creator:main
#
# Input directory:
# /anaconda-rpms/ (Anaconda RPM files for the build)
#
# Output directory:
# /images (Where the boot.iso will be stored)
#

set -eux

# pre-create loop devices manually. In the container you can't use losetup for that.
mknod -m 0660 /dev/loop0 b 7 0  2> /dev/null || true
mknod -m 0660 /dev/loop1 b 7 1  2> /dev/null || true

INPUT_RPMS=/anaconda-rpms/
OUT_DIR=/images/
REPO_DIR=/tmp/anaconda-rpms/

# create repo from provided Anaconda RPMs
mkdir -p $REPO_DIR
cp -a $INPUT_RPMS/* $REPO_DIR || echo "RPM files can't be copied!"  # We could just do the build with official repositories only
createrepo_c $REPO_DIR

# build boot.iso with our rpms
. /etc/os-release
# The download.fedoraproject.org automatic redirector often selects download-ib01.f.o. for GitHub's cloud, which is too unreliable; use a mirror
# The --volid argument can cause different network interface naming: https://github.com/rhinstaller/kickstart-tests/issues/448
{% if distro_name == "fedora" %}
lorax -p Fedora -v "$VERSION_ID" -r "$VERSION_ID" \
{% if distro_release == "rawhide" %}
      --volid Fedora-S-dvd-x86_64-rawh \
{% else %}
      --volid Fedora-S-dvd-x86_64-{$ distro_release $} \
{% endif %}
      -s http://dl.fedoraproject.org/pub/fedora/linux/development/{$ distro_release $}/Everything/x86_64/os/ \
{% elif distro_name == "rhel" and distro_release == 10 %}
MAJOR_VERSION=${VERSION_ID%%.*}
MINOR_VERSION=${VERSION_ID#*.}

lorax -p RHEL -v "$MAJOR_VERSION" -r "$MINOR_VERSION" \
      --volid "RHEL-$MAJOR_VERSION-$MINOR_VERSION-BaseOS-x86_64" \
      --nomacboot \
      -s http://download.devel.redhat.com/rhel-{$ distro_release $}/nightly/RHEL-{$ distro_release $}/latest-RHEL-{$ distro_release $}/compose/BaseOS/x86_64/os/ \
      -s http://download.devel.redhat.com/rhel-{$ distro_release $}/nightly/RHEL-{$ distro_release $}/latest-RHEL-{$ distro_release $}/compose/AppStream/x86_64/os/ \
{% endif %}
      -s file://$REPO_DIR/ \
      "$@" \
      output || cp *.log "$OUT_DIR"

cp output/images/boot.iso "$OUT_DIR"

# fix permissions to user permissions on the built artifacts
chown -Rv --reference="$INPUT_RPMS" "$OUT_DIR"
